import React from 'react'
import {
  Divider,
  Card,
  Modal,
  Table,
  Tabs,
  Spin
} from 'antd'
import moment from 'moment'
import DescriptionList from 'components/DescriptionList'
import styles from './index.less'
import { sourceSystem, productType, contractOrderType, logisticsStatus, timeCheckout, quoteType, distributionWay, purchaseType } from 'utils/enumConfig'
import { LwjDownload } from 'components'
import LogisticsDetailModal from './LogisticsDetailModal'
import InstallationDetail from './InstallationDetail'
import { LwjPic4Absolute } from 'components'
import { checkAmount } from 'utils/utils';

const { Description } = DescriptionList
const TabPane = Tabs.TabPane

const ContractDetailModal = ({
  currentContractDetail = {},
  currentLogisticsDetail = {},
  logisticsDetailModalVisible,
  dispatch,
  logisticsSummaries,
  installationSummaries,
  spinLoading,
  isHashProduction,
  ...contractDetailModalProps
}) => {

  let loaded = _.isEmpty(currentContractDetail)

  // 处理操作日志->按照创建时间排序
  const handleLogs = _.sortBy(currentContractDetail.contractOrderActivitySummaries, (log) => {
    return -log.createTime
  })
  //第三方来源系统商品信息
  const sourceSystemDataSource = _.sortBy(currentContractDetail.commodityThirdSummary, (commodity) => {
    return -commodity.createTime
  })

  const logsColumns = [
    {
      title: '操作人',
      dataIndex: 'handlerName',
      key: 'handlerName',
      width: '10%',
      render: (text, record, index) => (record.handlerName)
    }, {
      title: '操作时间',
      dataIndex: 'handleTime',
      key: 'handleTime',
      width: '30%',
      render: (text, record, index) => (timeCheckout(moment(record.createTime).format('YYYY-MM-DD HH:mm:ss')))
    }, {
      title: '操作类型',
      dataIndex: 'memo',
      key: 'memo',
      width: '60%',
    }
  ]
  const sourceSystemColumns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '商品金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (text, record, index) => (record.amount.toFixed(2))
    }, {
      title: '商品图片',
      dataIndex: 'imgUrl',
      key: 'imgUrl',
      render: (record) => (
        <LwjPic4Absolute title='安装效果图' fileSrc={record} />
      )
    }, {
      title: '商品说明',
      dataIndex: 'description',
      key: 'description',
    }
    , {
      title: '商品规格',
      dataIndex: 'spec',
      key: 'spec',
    }
    , {
      title: '商品重量',
      dataIndex: 'weight',
      key: 'weight',
    }
    , {
      title: '商品数量',
      dataIndex: 'quantity',
      key: 'quantity',
    }
  ]

  const materielItemsColumns = [
    {
      title: '物料编码',
      dataIndex: 'code',
      key: 'code'
    }, {
      title: '物料名称',
      dataIndex: 'name',
      key: 'name'
    }, {
      title: '物料数量',
      dataIndex: 'quantity',
      key: 'quantity'
    }
  ]

  const logisticsOrderColumns = [
    {
      title: '订单信息',
      dataIndex: 'orderInfo',
      key: 'orderInfo',
      render: (text, record, index) => (
        <span>
          <span>合同号:{record.contractNum}</span>
        </span>)
    }, {
      title: '预计到货时间',
      dataIndex: 'estimatedArrivalAt',
      key: 'estimatedArrivalAt',
      render: (text, record, index) => (timeCheckout(moment(text).format('YYYY-MM-DD HH:mm:ss')))
    }, {
      title: '收货人信息',
      dataIndex: 'consignee',
      key: 'consignee',
      render: (text, record, index) => (
        <span>
          <span>{record.consignee}</span>
        </span>)
    }, {
      title: '物流状态',
      dataIndex: 'logisticsStatus',
      key: 'logisticsStatus',
      render: (text, record, index) => (
        <span>
          <span>{logisticsStatus[text]}</span>
        </span>)
    }, {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text, record, index) => (timeCheckout(moment(text).format('YYYY-MM-DD HH:mm:ss')))
    }, {
      title: '操作',
      dataIndex: 'handleType',
      key: 'handleType',
      render: (text, record, index) => (
        <span>
          <a onClick={() => onShowLogisticsDetail(record)}>查看</a>
        </span>
      )
    }
  ]

  // 合同详情 props
  const LogisticsDetailModalProps = {
    title: '物流详情',
    visible: logisticsDetailModalVisible,
    destroyOnClose: true,
    width: 1000,
    currentItem: currentLogisticsDetail,
    footer: null,
    onCancel(record) {
      dispatch({
        type: 'contractInProduction/hideLogisticsDetailModalVisible',
        payload: {}
      })
      dispatch({
        type: 'contractInProduction/setSpinLoading',
        payload: {
          spinLoading: false
        }
      });
    },
    dispatch,
  }

  /**
   * 查看物流信息详情
   * @param {*} record
   */
  const onShowLogisticsDetail = (record) => {
    dispatch({
      type: 'contractInProduction/showLogisticsDetailModalVisible',
      payload: {}
    })
    dispatch({
      type: 'contractInProduction/setCurrentLogisticsDetail',
      payload: record
    })
  }

  const summaries = logisticsSummaries
  let tabPanes = []
  if (summaries !== null && summaries !== undefined) {
    summaries.forEach((item, index) => {
      tabPanes.push(
        <TabPane tab={'单号:' + item.orderNum} key={index}>
          {logisticsDetailModalVisible && <LogisticsDetailModal {...LogisticsDetailModalProps} />}
        </TabPane>
      )
    })
  }

  const logisticsTabsChange = (index) => {
    if (logisticsSummaries !== null && logisticsSummaries !== undefined && logisticsSummaries !== {}) {
      onShowLogisticsDetail(logisticsSummaries[index])
    }
  }
  const commodityColumns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '物料',
      dataIndex: 'materiel',
      key: 'materiel',
      render: (text, record, index) => (
        record.materielSnapshotList.map(element => {
          return element.materialCode + "*" + element.materialNum * record.number + ";"
        })
      )
    },
    {
      title: '商品图片',
      dataIndex: 'coverPath',
      key: 'coverPath',
      width: "10%",
      render: (record) => (
        <LwjPic4Absolute title='商品图片' fileSrc={record} />
      )
    }
    ,
    {
      title: '商品单价',
      dataIndex: 'channelPrice',
      key: 'channelPrice',
      render: (text, record, index) => (checkAmount(record.channelPrice))
    }
    , {
      title: '商品数量',
      dataIndex: 'number',
      key: 'number',
    }
    , {
      title: '实付金额',
      dataIndex: 'realPrice',
      key: 'realPrice',
      render: (text, record, index) => (checkAmount(record.channelPrice * record.number))
    }
  ]

  const parentOnchange = (index) => {
    if (index === '6') {
      dispatch({
        type: 'contractInProduction/getTms',
        payload: currentContractDetail
      })
      dispatch({
        type: 'contractInProduction/showLogisticsDetailModalVisible',
        payload: {}
      })
    }

    if (index === '7') {
      dispatch({
        type: 'contractInProduction/getIns',
        payload: currentContractDetail
      })
      dispatch({
        type: 'contractInProduction/setSpinLoading',
        payload: {
          spinLoading: true
        }
      });
    }
  }
  const installOrArrive = currentContractDetail.contractOrderType === "CUSTOMIZE" ? "合同安装时间" : "合同到货时间";
  const buildAllHardWare = (record) => {
    const handle = _.isEmpty(record.handle) ? "" : record.handle + " x" + record.handleNum + ";";
    const coverType = _.isEmpty(record.coverType) ? "" : record.coverType + " x" + record.coverTypeNum + ";";
    const straightening = _.isEmpty(record.straightening) ? "" : record.straightening + " x" + record.straighteningNum + ";"

    return handle + coverType + straightening;
  }

  const designDoorColumns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name'
    }, {
      title: '花色厚度',
      dataIndex: 'thickness',
      key: 'thickness'
    }, {
      title: '成品H',
      dataIndex: 'productH',
      key: 'productH',
      width: '10%'
    }, {
      title: '成品W',
      dataIndex: 'productW',
      key: 'productW',
      width: '10%'
    }, {
      title: '开门方向',
      dataIndex: 'doorDirect',
      key: 'doorDirect'
    }, {
      title: '竖横纹',
      dataIndex: 'vertical',
      key: 'vertical'
    }, {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity'
    }, {
      title: '面积',
      dataIndex: 'area',
      key: 'area',
      width: '8%',
      render: (text, record) => checkAmount((record.productH * record.productW * record.quantity) / 1000000)
    }, {
      title: '单价',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      width: '10%',
      render: (text, record) => checkAmount(text)
    }, {
      title: '小计',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      width: '10%',
      render: (text, record) => checkAmount(text)
    }
  ]
  const isDoorDesign = currentContractDetail.productType === 'DOORPLANK';

  return (
    <Modal {...contractDetailModalProps}>
      {!loaded && <Tabs onChange={parentOnchange} defaultActiveKey="1" type="card">
        <TabPane tab="基础信息" key="1">
          <Card>
            <DescriptionList
              size="small">
              <Description term="合同号">{currentContractDetail.contractNum}</Description>
              <Description term="合同类型">{contractOrderType[currentContractDetail.contractOrderType]}</Description>
              <Description term="产品类型">{productType[currentContractDetail.productType]}</Description>
              <Description term="是否需要设计">{currentContractDetail.designNeeded ? '是' : '否'}</Description>
              <Description term="是否推送丽维家">{currentContractDetail.pushToOMSNeeded ? '是' : '否'}</Description>
              <Description term="采购方式">{purchaseType[currentContractDetail.purchaseType]}</Description>
              <Description
                term="合同签订时间">{timeCheckout(moment(currentContractDetail.orderContractAt).format('YYYY-MM-DD HH:mm:ss'))}</Description>
              <Description
                term={installOrArrive}>{timeCheckout(moment(currentContractDetail.installContractAt).format('YYYY-MM-DD HH:mm:ss'))}</Description>
            </DescriptionList>
          </Card>
        </TabPane>
        {!_.isEmpty(currentContractDetail.designAttachment) && <TabPane tab="设计信息" key="2">
          <Card>
            {currentContractDetail.designNeeded && <DescriptionList
              size="small">
              <Description
                term="测量时间">{timeCheckout(moment(currentContractDetail.measuredAt).format('YYYY-MM-DD HH:mm:ss'))}</Description>
              <Description term="测量设计师姓名">{currentContractDetail.measureDesignerName}</Description>
              <Description term="测量设计师手机号">{currentContractDetail.measureDesignerPhoneNum}</Description>

              <Description term="测量图纸">{<LwjDownload title={'点击下载'}
                targetUrl={currentContractDetail.measuredPictureAttachment} />}</Description>
              <Description term="现场图片">{<LwjDownload title={'点击下载'}
                targetUrl={currentContractDetail.scenePictureAttachment} />}</Description>
              {!_.isEmpty(currentContractDetail.backupDesignAttachment) && <Description term="原设计方案">{<LwjDownload title={'点击下载'} targetUrl={currentContractDetail.backupDesignAttachment} />}</Description>}
              <Description term="下推设计方案">{<LwjDownload title={'点击下载'} targetUrl={currentContractDetail.designAttachment} />}</Description>
              {currentContractDetail.status === 'DENIED_DESIGN' &&
                <Description term="设计不通过原因">{currentContractDetail.designDeniedReason}</Description>}
            </DescriptionList>}
            {!currentContractDetail.designNeeded && <DescriptionList
              size="small">
              <Description term="商家设计师姓名">{currentContractDetail.designerUserName}</Description>
              <Description term="商家设计师手机号">{currentContractDetail.designerUserPhoneNum}</Description>
              {!_.isEmpty(currentContractDetail.backupDesignAttachment) && <Description term="原设计方案">{<LwjDownload title={'点击下载'}
                targetUrl={currentContractDetail.backupDesignAttachment} />}</Description>}
              <Description term="下推设计方案">{<LwjDownload title={'点击下载'}
                targetUrl={currentContractDetail.designAttachment} />}</Description>
              {currentContractDetail.status === 'DENIED_DESIGN' &&
                <Description term="设计不通过原因">{currentContractDetail.designDeniedReason}</Description>}
            </DescriptionList>}
          </Card>
        </TabPane>}
        {!isDoorDesign && <TabPane tab="商品信息" key="11">
          <Card>
            <DescriptionList
              size="small"
              style={{ marginBottom: 32 }}>
              <Description
                term="来源系统">
                {sourceSystem[currentContractDetail.sourceSystem === null ? "NULL" : currentContractDetail.sourceSystem]}
              </Description>
              <Description
                term="下单备注">
                {currentContractDetail.goodsDescription}
              </Description>
              <Description
                term="配送方式">
                {distributionWay[currentContractDetail.distributionWay]}
              </Description>
              <Description
                term="来源订单号">
                {currentContractDetail.salesOrderNum}
              </Description>
            </DescriptionList>
            <Table
              style={{ marginBottom: 24 }}
              pagination={false}
              dataSource={currentContractDetail.goodsSnapshots}
              columns={commodityColumns}
              rowKey="createTime" />
          </Card>
        </TabPane>}
        {isDoorDesign && <TabPane tab="定制品信息" key="12">
          <Card>
            <DescriptionList
              size="small"
              style={{ marginBottom: 32 }}>
              <Description
                term="来源系统">
                {sourceSystem[currentContractDetail.sourceSystem === null ? "NULL" : currentContractDetail.sourceSystem]}
              </Description>
              <Description
                term="商城订单号">
                {currentContractDetail.sourceOrderNum}
              </Description>
              <Description
                term="配送方式">
                {distributionWay[currentContractDetail.distributionWay]}
              </Description>
              <Description
                term="金额总计">
                {checkAmount(currentContractDetail.orderAmount)}
              </Description>
              {currentContractDetail.designAttachment && <Description term="设计方案">{<LwjDownload title={'点击下载'} targetUrl={currentContractDetail.designAttachment} />}</Description>}
            </DescriptionList>
            <Table
              style={{ marginBottom: 24 }}
              pagination={false}
              dataSource={currentContractDetail.customizeGoodsSummaries}
              expandedRowRender={record =>
                <div style={{ position: 'inline' }}>
                五金配件: {buildAllHardWare(record)}
                  <span style={{ margin: 0 }}>备注:{_.isEmpty(record.memo) ? "暂无" : record.memo} ;</span>
                  <span style={{ margin: 0 }}>铣型:{record.millingType ? "有" : "无"} ;</span>
                  <span style={{ margin: 0 }}>拉槽:{record.slot ? "有" : "无"} ;</span>
                  <span style={{ margin: 0 }}>单双面:{record.bothSide} ;</span>
                </div>
              }
              columns={designDoorColumns}
              rowKey="createTime" />
          </Card>
        </TabPane>}
        {!_.isEmpty(currentContractDetail.orderQuoteSummary) && <TabPane tab="报价信息" key="3">
          <Card>
            <DescriptionList
              size="small"
              style={{ marginBottom: 32 }}>
              <Description
                term="原合同金额">{currentContractDetail.orderQuoteSummary.preOrderAmount.toFixed(2)}</Description>
              <Description
                term="装修返点金额">{currentContractDetail.orderQuoteSummary.decorationRebateAmount.toFixed(2)}</Description>
              <Description
                term="样柜返点金额">{currentContractDetail.orderQuoteSummary.cabinetRebateAmount.toFixed(2)}</Description>
              <Description term="活动优惠金额">{currentContractDetail.orderQuoteSummary.eventsAmount.toFixed(2)}</Description>
              <Description term="合同金额">{currentContractDetail.orderQuoteSummary.orderAmount.toFixed(2)}</Description>
              <Description term="报价备注">{currentContractDetail.orderQuoteSummary.memo}</Description>
              {currentContractDetail.status === 'DENIED_QUOTED' &&
                <Description term="报价不通过原因">{currentContractDetail.orderQuoteSummary.quoteDeniedReason}</Description>}
              <Description term="原报价方案">{<LwjDownload title={'点击下载'} targetUrl={currentContractDetail.orderQuoteSummary.backupQuoteAttachment} />}</Description>
              <Description term="报价方案">{<LwjDownload title={'点击下载'}
                targetUrl={currentContractDetail.orderQuoteSummary.quoteAttachment} />}</Description>
              <Description term={quoteType[currentContractDetail.orderQuoteSummary.deductionType]}>{currentContractDetail.orderQuoteSummary.orderAmount.toFixed(2)}</Description>
            </DescriptionList>
          </Card>
        </TabPane>}
        {!_.isEmpty(currentContractDetail.orderPublishInfoSummary) && !_.isEmpty(currentContractDetail.orderPublishInfoSummary.contractAmount) && <TabPane tab="下单信息" key="4">
          <Card>
            <DescriptionList
              size="small"
              style={{ marginBottom: 32 }}>
              <Description term="合同号">{currentContractDetail.orderPublishInfoSummary.contractNum}</Description>
              <Description
                term="合同签订时间">{timeCheckout(moment(currentContractDetail.orderPublishInfoSummary.contractSignedAt).format('YYYY-MM-DD HH:mm:ss'))}</Description>
              {!_.isEmpty(currentContractDetail.orderPublishInfoSummary.contractInstalledAt) &&
                <Description term="合同安装时间">
                  {timeCheckout(moment(currentContractDetail.orderPublishInfoSummary.contractInstalledAt).format('YYYY-MM-DD HH:mm:ss'))}
                </Description>}
              {!_.isEmpty(currentContractDetail.orderPublishInfoSummary.contractArrivalAt) &&
                <Description term="合同到货时间">
                  {timeCheckout(moment(currentContractDetail.orderPublishInfoSummary.contractArrivalAt).format('YYYY-MM-DD HH:mm:ss'))}
                </Description>}
              <Description
                term="合同金额">{currentContractDetail.orderPublishInfoSummary.contractAmount.toFixed(2)}</Description>
              <Description term="收货人姓名">{currentContractDetail.orderPublishInfoSummary.receiptUserName}</Description>
              <Description
                term="收货人手机号">{currentContractDetail.orderPublishInfoSummary.receiptUserPhoneNum}</Description>
              <Description term="收货人地址">{currentContractDetail.orderPublishInfoSummary.receiptAddress}</Description>
              {currentContractDetail.contractOrderType === 'CUSTOMIZE' &&
                <Description term="CAD图纸">{<LwjDownload title={'点击下载'}
                  targetUrl={currentContractDetail.orderPublishInfoSummary.cadAttachment} />}</Description>}
              {currentContractDetail.contractOrderType === 'END' &&
                <Description term="成品订单附件">{<LwjDownload title={'点击下载'}
                  targetUrl={currentContractDetail.orderPublishInfoSummary.endOrderAttachment} />}</Description>}
            </DescriptionList>
            {currentContractDetail.contractOrderType === 'END' &&
              <div>
                <Divider style={{ marginBottom: 32 }} />
                <div className={styles.title}>物料信息</div>
                <Table
                  style={{ marginBottom: 24 }}
                  pagination={false}
                  dataSource={currentContractDetail.orderPublishInfoSummary.materielItems}
                  columns={materielItemsColumns}
                  rowKey="code" />
              </div>}
          </Card>
        </TabPane>}
        {/* {currentContractDetail.sourceOrderNum && currentContractDetail.sourceSystem !== "SAlES_MARKET" && currentContractDetail.sourceSystem !== "WX_LITE" && <TabPane tab="第三方记录" key="9">
          <Card>
            <DescriptionList
              size="small"
              style={{ marginBottom: 32 }}>
              <Description
                term="来源系统">
                {sourceSystem[currentContractDetail.sourceSystem === null ? "NULL" : currentContractDetail.sourceSystem]}
              </Description>
              <Description
                term="第三方订单号">
                {currentContractDetail.sourceOrderNum}
              </Description>
            </DescriptionList>
            <Table
              style={{ marginBottom: 24 }}
              dataSource={sourceSystemDataSource}
              columns={sourceSystemColumns}
              rowKey="createTime" />
          </Card>
        </TabPane>} */}
        <TabPane tab="操作记录" key="5">
          <Table
            style={{ marginBottom: 24 }}
            pagination={false}
            dataSource={handleLogs}
            columns={logsColumns}
            rowKey="createTime" />
        </TabPane>

        {isHashProduction && <TabPane tab="物流信息" key="6">
          {!loaded && summaries !== null && summaries !== undefined && summaries.length !== 0 &&
            <Tabs onChange={logisticsTabsChange} defaultActiveKey="0" type="card">
              {tabPanes}
            </Tabs>}
        </TabPane>}
        <TabPane tab="安装信息" key="7">
          <div style={{ textAlign: 'center' }}>
            <Spin spinning={spinLoading} />
          </div>
          {installationSummaries && installationSummaries.installInfo &&
            <InstallationDetail currentItem={installationSummaries} dispatch={dispatch} />}
        </TabPane>
      </Tabs>}
    </Modal>
  )
}

export default ContractDetailModal
